package cn.zhouyafeng.itchat4j.core;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.game.GameEnum;
import cn.zhouyafeng.itchat4j.game.GuessNumberGame;
import cn.zhouyafeng.itchat4j.game.SeePicGame;
import cn.zhouyafeng.itchat4j.service.impl.LoginServiceImpl;
import cn.zhouyafeng.itchat4j.utils.enums.MsgCodeEnum;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.CommonTools;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;

/**
 * 消息处理中心
 * 
 * @author https://github.com/yaphone
 * @date 创建时间：2017年5月14日 下午12:47:50
 * @version 1.0
 *
 */
public class MsgCenter {
	private static Logger LOG = LoggerFactory.getLogger(MsgCenter.class);

	private static Core core = Core.getInstance();

	/**
	 * 接收消息，放入队列
	 * 
	 * @author https://github.com/yaphone
	 * @date 2017年4月23日 下午2:30:48
	 * @param msgList
	 * @return
	 */
	public static JSONArray produceMsg(JSONArray msgList) {
		JSONArray result = new JSONArray();
		for (int i = 0; i < msgList.size(); i++) {
			JSONObject msg = new JSONObject();
			JSONObject m = msgList.getJSONObject(i);
			m.put("groupMsg", false);// 是否是群消息
			if (m.getString("FromUserName").contains("@@") || m.getString("ToUserName").contains("@@")) { // 群聊消息
				if (m.getString("FromUserName").contains("@@")
						&& !core.getGroupIdList().contains(m.getString("FromUserName"))) {
					core.getGroupIdList().add((m.getString("FromUserName")));
				} else if (m.getString("ToUserName").contains("@@")
						&& !core.getGroupIdList().contains(m.getString("ToUserName"))) {
					core.getGroupIdList().add((m.getString("ToUserName")));
				}
				// 群消息与普通消息不同的是在其消息体（Content）中会包含发送者id及":<br/>"消息，这里需要处理一下，去掉多余信息，只保留消息内容
				if (m.getString("Content").contains("<br/>")) {
					String content = m.getString("Content").substring(m.getString("Content").indexOf("<br/>") + 5);
					m.put("Content", content);
					m.put("groupMsg", true);
				}
			} else {
				CommonTools.msgFormatter(m, "Content");
			}
			if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_TEXT.getCode())) { // words
																						// 文本消息
				if (m.getString("Url").length() != 0) {
					String regEx = "(.+?\\(.+?\\))";
					Matcher matcher = CommonTools.getMatcher(regEx, m.getString("Content"));
					String data = "Map";
					if (matcher.find()) {
						data = matcher.group(1);
					}
					msg.put("Type", "Map");
					msg.put("Text", data);
				} else {
					msg.put("Type", MsgTypeEnum.TEXT.getType());
					msg.put("Text", m.getString("Content"));
				}
				m.put("Type", msg.getString("Type"));
				m.put("Text", msg.getString("Text"));
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_IMAGE.getCode())
					|| m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_EMOTICON.getCode())) { // 图片消息
				m.put("Type", MsgTypeEnum.PIC.getType());
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VOICE.getCode())) { // 语音消息
				m.put("Type", MsgTypeEnum.VOICE.getType());
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VERIFYMSG.getCode())) {// friends
				// 好友确认消息
				// MessageTools.addFriend(core, userName, 3, ticket); // 确认添加好友
				m.put("Type", MsgTypeEnum.VERIFYMSG.getType());

			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_SHARECARD.getCode())) { // 共享名片
				m.put("Type", MsgTypeEnum.NAMECARD.getType());

			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_VIDEO.getCode())
					|| m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_MICROVIDEO.getCode())) {// viedo
				m.put("Type", MsgTypeEnum.VIEDO.getType());
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_MEDIA.getCode())) { // 多媒体消息
				m.put("Type", MsgTypeEnum.MEDIA.getType());
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_STATUSNOTIFY.getCode())) {// phone
				// init
				// 微信初始化消息

			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_SYS.getCode())) {// 系统消息
				m.put("Type", MsgTypeEnum.SYS.getType());
			} else if (m.getInteger("MsgType").equals(MsgCodeEnum.MSGTYPE_RECALLED.getCode())) { // 撤回消息

			} else {
				LOG.info("Useless msg");
			}
			LOG.info("收到消息一条，来自: " + m.getString("FromUserName")+" "+m.getString("Type") +" " + m.getString("Content"));
			result.add(m);
		}
		return result;
	}

	/**
	 * 消息处理
	 * 
	 * @author https://github.com/yaphone
	 * @date 2017年5月14日 上午10:52:34
	 * @param msgHandler
	 */
	public static void handleMsg(IMsgHandlerFace msgHandler) {
		while (true) {
			try {
				if (core.getMsgList().size() > 0 && core.getMsgList().get(0).getContent() != null) {
					if (core.getMsgList().get(0).getContent().length() > 0) {
						BaseMsg msg = core.getMsgList().get(0);
						if (msg.getType() != null) {
							try {
//							LOG.info(JSONObject.toJSONString(msg));

								if("启用liam".equals(msg.getText())){
									core.getMyGroupIds().add(core.getMsgList().get(0).getFromUserName());
									MessageTools.sendMsgById("启动成功！你可以说：\nliam看312照片\nliam猜数字\nliam讲个笑话", core.getMsgList().get(0).getFromUserName());
								}else if ("关闭liam".equals(msg.getText())){
									core.getMyGroupIds().remove(core.getMsgList().get(0).getFromUserName());
									MessageTools.sendMsgById("已关闭liam机器人", core.getMsgList().get(0).getFromUserName());

								}else if(msg.getText().startsWith("liam")
										&& core.getMyGroupIds().contains(core.getMsgList().get(0).getFromUserName())){


									if (msg.getType().equals(MsgTypeEnum.TEXT.getType())) {

										// 判断是否游戏相关
										if(!isGame(msg.getText(),core.getMsgList().get(0).getFromUserName())){
											String result = msgHandler.textMsgHandle(msg);
											MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
										}

									} else if (msg.getType().equals(MsgTypeEnum.PIC.getType())) {

										String result = msgHandler.picMsgHandle(msg);
										MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
									} else if (msg.getType().equals(MsgTypeEnum.VOICE.getType())) {
										String result = msgHandler.voiceMsgHandle(msg);
										MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
									} else if (msg.getType().equals(MsgTypeEnum.VIEDO.getType())) {
										String result = msgHandler.viedoMsgHandle(msg);
										MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
									} else if (msg.getType().equals(MsgTypeEnum.NAMECARD.getType())) {
										String result = msgHandler.nameCardMsgHandle(msg);
										MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
									} else if (msg.getType().equals(MsgTypeEnum.SYS.getType())) { // 系统消息
										msgHandler.sysMsgHandle(msg);
									} else if (msg.getType().equals(MsgTypeEnum.VERIFYMSG.getType())) { // 确认添加好友消息
										String result = msgHandler.verifyAddFriendMsgHandle(msg);
										MessageTools.sendMsgById(result,
												core.getMsgList().get(0).getRecommendInfo().getUserName());
									} else if (msg.getType().equals(MsgTypeEnum.MEDIA.getType())) { // 多媒体消息
										String result = msgHandler.mediaMsgHandle(msg);
										MessageTools.sendMsgById(result, core.getMsgList().get(0).getFromUserName());
									}
								}

								LOG.info("当前liam机器启用数量:" +core.getMyGroupIds().size());

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					core.getMsgList().remove(0);
				}
				try {
					TimeUnit.MILLISECONDS.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}catch (Exception e){
				e.printStackTrace();
			}

		}
	}

	private static boolean isGame(String result, String key) {
		if("liam猜数字".equals(result)){
			GuessNumberGame.start(key);
			return true;
		}else if("liam看照片".equals(result)){
			SeePicGame.seePic(key,GameEnum.SEE_PIC.getCode());
			return true;
		}else if("liam看312照片".equals(result)){
			SeePicGame.seePic(key,GameEnum.SEE_PIC_312.getCode());
			return true;
		}else if(result.contains("关闭猜数字")){
			GuessNumberGame.end(key);
			return true;
		}

		String gameCode = GlobalConfig.currGameMap.get(key);
		if(StringUtils.isNotBlank(gameCode)){
			doGame(key,gameCode,result);
			return true;
		}


		return false;
	}

	private static void doGame(String key, String gameCode, String result) {
		if(gameCode.equals(GameEnum.GUESS_NUMBER.getCode())){
			result = result.replaceAll("liam","");
			result = result.replaceAll(" ","");
			try{
				Integer r = Integer.valueOf(result);
				r = GuessNumberGame.compare(key,r);
				if(r == 0){
					MessageTools.sendMsgById("恭喜答对了！答案"+result, key);
					GuessNumberGame.end(key);
				}else if (r == 1){
					MessageTools.sendMsgById(result+"太大了！", key);
				}else{
					MessageTools.sendMsgById(result+"太小了！", key);
				}
			}catch (Exception e){
				MessageTools.sendMsgById("答案只能是数字，想停止游戏可以说：liam关闭猜数字", core.getMsgList().get(0).getFromUserName());
			}

		}
	}

}
